package com.push.web.controller;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hankcs.hanlp.HanLP;
import com.push.common.config.TransConfig;
import com.push.common.utils.MD5;
import com.push.common.utils.StringUtils;
import com.push.common.utils.httpclient.HttpClientUtil;
import com.push.web.domain.BizCollection;
import com.push.web.service.IBizCollectionService;
import com.push.web.utils.WordUtil;
import com.push.web.vo.ExpressBodyVo;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.push.common.annotation.Log;
import com.push.common.core.controller.BaseController;
import com.push.common.core.domain.AjaxResult;
import com.push.common.enums.BusinessType;
import com.push.web.domain.BizArticle;
import com.push.web.service.IBizArticleService;
import com.push.common.utils.poi.ExcelUtil;
import com.push.common.core.page.TableDataInfo;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.push.common.utils.StringUtils.delHtmlTags;

/**
 * 信息管理Controller
 *
 * @author yanxi
 * @date 2022-03-10
 */
@RestController
@RequestMapping("/information/article")
public class BizArticleController extends BaseController
{
    @Autowired
    private IBizArticleService bizArticleService;

    @Autowired
    private TransConfig transConfig;

    @Autowired
    private IBizCollectionService bizCollectionService;

    /**
     * 查询信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('information:article:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizArticle bizArticle)
    {
        startPage();
        List<BizArticle> list = bizArticleService.selectBizArticleList(bizArticle);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('information:article:list')")
    @GetMapping("/listByIds")
    public TableDataInfo listByIds(BizArticle bizArticle)
    {
        startPage();
        BizCollection bizCollection = bizCollectionService.selectBizCollectionById(bizArticle.getCollectionId());
        if (null != bizCollection && StringUtils.isNotEmpty(bizCollection.getArticleIds())){
            bizArticle.setArticleIds(bizCollection.getArticleIds());
            List<BizArticle> list = bizArticleService.selectBizArticleList(bizArticle);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }

    }

    /**
     * 导出信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('information:article:export')")
    @Log(title = "信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(@RequestBody String ids)
    {
        List<Long> aids=Arrays.stream(ids.split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList());
        List<BizArticle> list = bizArticleService.selectBizArticleByIds(aids);
        ExcelUtil<BizArticle> util = new ExcelUtil<BizArticle>(BizArticle.class);
        return util.exportExcel(list, "信息数据");
    }

    @PreAuthorize("@ss.hasPermi('information:article:export')")
    @Log(title = "信息管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizArticle bizArticle)
    {
        List<BizArticle> list = bizArticleService.selectBizArticleList(bizArticle);
        ExcelUtil<BizArticle> util = new ExcelUtil<BizArticle>(BizArticle.class);
        return util.exportExcel(list, "信息数据");
    }


    @PreAuthorize("@ss.hasPermi('information:article:export')")
    @Log(title = "信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportByCid")
    public AjaxResult exportByCid(@RequestBody BizArticle bizArticle)
    {
        BizCollection bizCollection = bizCollectionService.selectBizCollectionById(bizArticle.getCollectionId());
        List<Long> aids=Arrays.stream(bizCollection.getArticleIds().split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList());
        List<BizArticle> list = bizArticleService.selectBizArticleByIds(aids);
        ExcelUtil<BizArticle> util = new ExcelUtil<BizArticle>(BizArticle.class);
        return util.exportExcel(list, "信息数据");
    }

    /**
     * 获取信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('information:article:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(bizArticleService.selectBizArticleById(id));
    }

    /**
     * 新增信息管理
     */
    @PreAuthorize("@ss.hasPermi('information:article:add')")
    @Log(title = "信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizArticle bizArticle)
    {
        return toAjax(bizArticleService.insertBizArticle(bizArticle));
    }

    @PreAuthorize("@ss.hasPermi('information:article:add')")
    @Log(title = "信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/remove")
    public AjaxResult removeArticle(@RequestBody BizArticle bizArticle)
    {
        BizCollection bizCollection = bizCollectionService.selectBizCollectionById(bizArticle.getCollectionId());
        List<Long> aids=Arrays.stream(bizCollection.getArticleIds().split(",")).map(s->Long.parseLong(s.trim())).collect(Collectors.toList());
        aids.removeIf(val -> val.equals(bizArticle.getId()));
        bizCollection.setArticleIds(aids.stream().map(Long -> Long.toString()).collect(Collectors.joining(",")));
        return toAjax(bizCollectionService.updateBizCollection(bizCollection));
    }



    /**
     * 修改信息管理
     */
    @PreAuthorize("@ss.hasPermi('information:article:edit')")
    @Log(title = "信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizArticle bizArticle)
    {
        return toAjax(bizArticleService.updateBizArticle(bizArticle));
    }

    /**
     * 删除信息管理
     */
    @PreAuthorize("@ss.hasPermi('information:article:remove')")
    @Log(title = "信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizArticleService.deleteBizArticleByIds(ids));
    }

    @PostMapping("/extractAbstract")
    public AjaxResult extractAbstract(@RequestBody BizArticle bizArticle){
        try{
            List<String> sentenceList = HanLP.extractSummary(delHtmlTags(bizArticle.getContentsOrg()),10);
            if(sentenceList.size() > 0){
                String abstact = sentenceList.toString();
                return AjaxResult.success(abstact.substring(1,abstact.lastIndexOf("]")));
            } else {
                return AjaxResult.success("");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @RequestMapping(value = "/exportWord", method = {RequestMethod.POST, RequestMethod.GET}, produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void exportWord(@RequestBody ExpressBodyVo expressBody, HttpServletResponse resp, HttpServletRequest req) throws IOException{
        WordUtil wordUtil = new WordUtil();
        List<BizArticle> articles = bizArticleService.selectBizArticleByIds(expressBody.getIds());
        wordUtil.createWord(expressBody, articles, resp, req);
        System.out.println("导出word模板成功");
    }


    @PostMapping("/trans")
    public AjaxResult trans(@RequestBody BizArticle bizArticle){
        bizArticle = bizArticleService.selectBizArticleById(bizArticle.getId());
        if(StringUtils.isContainChinese(bizArticle.getTitleOrg())){
            bizArticle.setTitleCn(bizArticle.getTitleOrg());
        } else {
            String transWord = getTransResult(bizArticle.getTitleOrg(), "auto", "zh");
            System.out.println("原始标题："+bizArticle.getTitleOrg());
            System.out.println("翻译标题："+transWord);
            JSONObject resultObj = JSONObject.parseObject(transWord);
            JSONArray jsonArray = resultObj.getJSONArray("trans_result");
            if (jsonArray.size() > 0){
                bizArticle.setTitleCn(jsonArray.getJSONObject(0).getString("dst"));
            }
        }
        bizArticleService.updateBizArticle(bizArticle);
        return AjaxResult.success();
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpClientUtil.doGet(transConfig.getTransUrl(), params,false).getContent();
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", transConfig.getAppid());
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = transConfig.getAppid() + query + salt + transConfig.getSecurityKey();
        params.put("sign", MD5.md5(src));

        return params;
    }
}
